import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import { getUserPermission, getUserInfo } from '@/api/user'
import store from '@/store'
import { flatAllPermissionData, getFlatAllPermissionDataIdList } from '@/utils/permission'

export interface IUserState {
  routerPermission: string[]
  buttonPermission: string[]
}

export interface IUserInfoState {
  userId?: string
  logoutUrl?: string
  userIcon?: string
  realname?: string
  manageScopeType?: string
  isSuperAdmin?: boolean
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: 不可达代码错误
@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  public routerPermission: string[] = []
  public buttonPermission: string[] = []
  public permissionList: any = {}
  public userInfo: IUserInfoState = {}

  @Mutation
  private SET_ROUTER_PERMISSION(routerPermission: string[]) {
    this.routerPermission = routerPermission
  }

  @Mutation
  private SET_BUTTON_PERMISSION(buttonPermission: string[]) {
    this.buttonPermission = buttonPermission
  }

  @Mutation
  private SET_PERMISSION_LIST(data: any) {
    this.permissionList = data
  }

  @Mutation
  private SET_USERINFO(data: any) {
    this.userInfo = data
  }

  @Action
  public SetButtonPermission(buttonPermission: string[]) {
    this.SET_BUTTON_PERMISSION(buttonPermission)
  }

  @Action
  public SetRouterPermission(routerPermission: string[]) {
    this.SET_ROUTER_PERMISSION(routerPermission)
  }

  @Action
  public SetPermissionList(data: any) {
    this.SET_PERMISSION_LIST(data)
  }

  @Action
  public ResetPermission() {
    this.SET_ROUTER_PERMISSION([])
    this.SET_BUTTON_PERMISSION([])
    this.SET_PERMISSION_LIST({})
    location.reload()
  }

  @Action
  public async GetUserInfo() {
    return new Promise(async (resolve) => {
      let result = null
      const res = await getUserInfo()
      if (res && res.code === '0' && res.data) {
        result = res.data
        this.SET_USERINFO(result || {})
      }
      resolve(result)
    })
  }

  @Action
  public async GetUserPermission() {
    return new Promise(async (resolve) => {
      let result = null
      const res = await getUserPermission()
      // return
      if (res && res.code === '0' && res.data) {
        const permissionList = flatAllPermissionData(res.data)
        const buttonPermission = getFlatAllPermissionDataIdList(permissionList, '2')
        const routerPermission = getFlatAllPermissionDataIdList(permissionList, '1').concat(
          buttonPermission,
        )
        this.SET_PERMISSION_LIST(permissionList)
        this.SET_ROUTER_PERMISSION(routerPermission)
        this.SET_BUTTON_PERMISSION(buttonPermission)
        result = {
          data: {
            permissionList,
            routerPermission,
            buttonPermission,
          },
        }
      }
      resolve(result)
    })
  }
}

export const UserModule = getModule(User)
